# -*- coding: utf-8 -*-

from django.http import JsonResponse
from django.db.models import Q

from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination

from blog.models import Blog
from blog.serializers import BlogSerializer, BlogLiteSerializer



class FaqsPagination(PageNumberPagination):
    '''自定义分页
    '''
    #默认每页显示的个数
    page_size = 20
    #可以动态改变每页显示的个数
    page_size_query_param = 'page_size'
    #页码参数
    page_query_param = 'page'
    #最多能显示多少页
    max_page_size = 100


class BlogListView(APIView):
    def get(self, request, format=None):
        q = Q(display="True")
        my_dict = {}
        q1 = Blog.objects.filter(q).order_by('-date')
        paginate = FaqsPagination()
        page_obj = paginate.paginate_queryset(q1, request)           
        serializer = BlogLiteSerializer(page_obj, many=True)
        return JsonResponse({"count": q1.count(), "results": serializer.data})
 
  
def show_blog_num(request):
    num = Blog.objects.filter(Q(display="True")).count()
    return JsonResponse({'num_blog': num}, safe=False)


def show_article(request):
    id_article = request.GET.get('id')
    q1 = Blog.objects.filter(Q(id__iexact=id_article))
    serializer = BlogSerializer(q1, many=True) 
    if serializer.data:
        return JsonResponse(serializer.data[0], safe=False)
    else:
        print("null")
        return JsonResponse({'name': ""}, safe=False)



